/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Core;

import Core.IConnectionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author Mr Bao
 */
public class ReaderThread extends Thread {

    protected IConnectionListener connectionListener;
    protected BufferedReader in;
    protected InputStream inputStream;
    protected boolean running = true;
    protected ConnectionHandler connectionHandler;

    public ReaderThread(IConnectionListener connectionListener, InputStream inputStream, ConnectionHandler connectionHandler) {
        this.connectionListener = connectionListener;
        this.inputStream = inputStream;
        this.connectionHandler = connectionHandler;
        in = new BufferedReader(new InputStreamReader(inputStream));
    }

    public void NormalRun() {
        try {
            String newLine;
            while (running && (newLine = in.readLine()) != null) {
                connectionListener.IncommingMessage(newLine);
            }
        } catch (Exception e) {
            running = false;
        }
    }

    public void Halt() {
        running = false;
    }

    @Override
    public void run() {
        NormalRun();
        connectionHandler.Shutdown(true);
    }
}
